<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * 角色
 *
 * @SWG\Model(id="Role",description="角色")
 * @SWG\Property(name="id",type="string",description="主键索引")
 * @SWG\Property(name="name",type="string",description="名称")
 * @SWG\Property(name="remark",type="string",description="简介")
 * @SWG\Property(name="actions",type="string",description="权限列表")
 */
class Role extends Model
{

	protected $table = 'roles';

	public static function boot()
	{
		parent::boot();

		static::saving(function ($model)
		{
			// 清理重名的控制器名。
			$model->actions = ',' . join(',', array_unique($model->action_array)) . ',';
            $model->menus =  implode(',', $model->menu_array);
		});
	}

	/**
	 * 拥有此角色的用户
	 */
	public function admins()
	{
		return $this->belongsToMany('App\Models\Admin', 'admin_role')->withTimestamps();
	}

	/**
	 * 支持赋值数组类型
	 */
	public function setActionsAttribute($value)
	{
		if (is_array($value)) {
			$this->attributes['actions'] = ',' . join(',', $value) . ',';
		} else {
			$this->attributes['actions'] = $value;
		}
	}

    public function setMenusAttribute($value)
    {
        if (is_array($value)) {
            $this->attributes['menus'] = implode(',', $value);
        } else {
            $this->attributes['menus'] = $value;
        }
    }

	/**
	 * 可操作控制器名数组
	 */
	public function getActionArrayAttribute()
	{
		return explode(',', trim((string) $this->actions, ','));
	}

    public function getMenuArrayAttribute()
    {
        return explode(',' , (string) $this->menus);
    }
}
